//
//  KBStatus.swift
//  KimboWeiBoSwift
//
//  Created by kimbo on 15/12/20.
//  Copyright © 2015年 kimbo. All rights reserved.
//

import UIKit
import SDWebImage

class KBStatus: NSObject {

    // MARK: - 属性
    /// 创建时间
    var created_at: String?
    
    /// 微博id
    var id: Int = 0
    
    /// 微博正文内容
    var text: String?
    
    /// 来源
    var source: String?
    
    /// 微博的配图 [String: AnyObject]
    var pic_urls: [[String: AnyObject]]? {
        didSet {
            let pic = pic_urls?.count ?? 0
            if pic == 0 { //没有图片
                return
            }
            
            storePictureURLs = [NSURL]()
            
            for dict in pic_urls! {
                let urlString = dict["thumbnail_pic"] as! String
                let url = NSURL(string: urlString)!
                storePictureURLs?.append(url)
            }
        }
    }
    
    /// 原创微博配图URL数组
    var storePictureURLs: [NSURL]?
    
    /// 微博的总配图URL数组(如果是原创微博显示原创配图URL，转发配图显示转发配图URL)
    var pictureURLs: [NSURL]? {
        return retweeted_status == nil ? storePictureURLs : retweeted_status?.storePictureURLs
    }
    
    /// cell的高度缓存
    var rowHeight: CGFloat?
    
    /// 被转发的微博
    var retweeted_status: KBStatus?
    
    /// 转发数
    var reposts_count: Int = 0
    
    /// 评论数
    var comments_count: Int = 0
    
    /// 表态数(赞)
    var attitudes_count: Int = 0
    
    /// 用户模型
    var user: KBUser?
    
    // MARK: - 方法
    /// 返回对应微博的cellID(有无转发微博)
    func cellID() -> String {
        return retweeted_status == nil ? KBStatusCellReuseIdentifier.normalCell.rawValue : KBStatusCellReuseIdentifier.forwardCell.rawValue
    }
    
    init(dict: [String: AnyObject]) {
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        // 解决键值不匹配报错问题
    }
    
    /// 拦截KVC,自己转user模型
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user" {
            
            if let dict = value as? [String: AnyObject] {
                user = KBUser(dict: dict)
            }
            
            return //一定要return!!!
        }
        
        // 自己字典转模型--被转微博
        if key == "retweeted_status" {
            if let dict = value as? [String: AnyObject] {
                retweeted_status = KBStatus(dict: dict)
            }
            return
        }
        
        super.setValue(value, forKey: key)
    }
    
    /// 实现description属性(打印)
    override var description: String {
        let pro = ["created_at", "id", "text", "source", "pic_urls", "reposts_count", "comments_count", "attitudes_count"]
        
        let dict = dictionaryWithValuesForKeys(pro)
        
        return "\n\t微博:\(dict)"
    }
    
    /// 加载微博
    class func loadStatus(since_id: Int, max_id: Int, finished: (statuses: [KBStatus]?, error: NSError?) -> ()) {
        KBNetWorkTool.sharedInstance.loadStatus(since_id, max_id: max_id) { (result, error) -> () in
            if result == nil || error != nil {
                finished(statuses: nil, error: error)
                return
            }
            
            // 来到这里，有微博数据,但不一定有status
            if let dictArr = result!["statuses"] as? [[String: AnyObject]] {
                
                var statuses = [KBStatus]()// 可变数组
                
                for dict in dictArr { //字典转模型
                    let status = KBStatus(dict: dict)
                    statuses.append(status)
                }
                //缓存单张图片
                cacheWebImage(statuses, finished: finished)
                
            } else {
                finished(statuses: nil, error: nil)
            }
        }
        
    }
    
    /// 缓存单张图片(其他不缓存)
    class func cacheWebImage(statuses: [KBStatus], finished: (statuses: [KBStatus]?, error: NSError?) -> ()) {
        
//        var length = 0 //图片大小
        
        let group = dispatch_group_create() //创建任务组
        
        for status in statuses {
            guard let urls = status.pictureURLs else {
                continue // 如果没有图片，继续下一个
            }
            
            if urls.count == 1 { //如果是单张图片，下载图片并计算大小
                let url = urls[0]
                
                dispatch_group_enter(group)
                
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, error, _, _, _) -> Void in
                    //要在判断是否错误前离开，否则一次有错误永远离开不了任务组
                    dispatch_group_leave(group)
                    
                    if error != nil {
                        return
                    }
                    
//                    if let data = UIImagePNGRepresentation(image) {
//                        length += data.length
//                    }
                    
                })
            }
        }
        //全部下载完，通知回调
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            finished(statuses: statuses, error: nil)
        }
    }
    
}

